package com.hth.eureka.consumer;

import com.hth.eureka.provider.HealthStatusService;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class ConsumerController {

    @Autowired
    EurekaClient client;

    @Autowired
    RestTemplate rest;

    @GetMapping("/string")
    public String string() {
        List<InstanceInfo> instances = client.getInstancesByVipAddress("EurekaProvider", false);
        String ans = null;
        if(instances.size()>0) {
            InstanceInfo ins = instances.get(0);

            String url = "http://" + ins.getAppName() + ":" + ins.getPort() + "/map";
            System.out.println(url);
            ans = rest.getForObject(url, String.class);
        }
        return ans;
    }

    @GetMapping("/rest")
    public String useRestTemplate() {
        // 自动处理URL
        String url ="http://EurekaProvider/map";
        String respStr = rest.getForObject(url, String.class);
        System.out.println(respStr);
        return respStr;
    }

    @Autowired
    HealthStatusService hsrv;

    @GetMapping("/health")
    public String health(@RequestParam("status") Boolean status) {

        hsrv.setStatus(status);
        return hsrv.getStatus();
    }

}
